#include "RenderWindow.h"
#include <iostream>

void RenderWindow::create(const char *p_title, int p_w, int p_h)
{
    // 创建窗口
    window = SDL_CreateWindow("Game Start",
                              SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED,
                              p_w, p_h,
                              SDL_WINDOW_SHOWN);
    if (window == NULL)
    {
        SDL_Log("创建SDL失败，%s", SDL_GetError());
        return;
    }
    // 创建渲染器，用于在窗口上绘制图形
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if (renderer == NULL)
    {
        SDL_Log("无法创建渲染器,%s", SDL_GetError());
        return;
    }
}

SDL_Texture *RenderWindow::loadTexture(const char *p_filePath)
{
    SDL_Texture *texture = NULL;
    texture = IMG_LoadTexture(renderer, p_filePath);

    if (texture == NULL)
        std::cout << "Failed to load texture. Error: " << SDL_GetError() << std::endl;

    return texture;
}

void RenderWindow::destroy()
{
    // 销毁渲染器
    SDL_DestroyRenderer(renderer);
    // 销毁窗口
    SDL_DestroyWindow(window);
}

void RenderWindow::clear()
{
    // 背景设置为白色
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
}

void RenderWindow::display()
{
    SDL_RenderPresent(renderer);
}

void RenderWindow::render(float p_x, float p_y, SDL_Texture *p_tex)
{
    SDL_Rect src; // 目标纹理
    src.x = 0;
    src.y = 0;
    SDL_QueryTexture(p_tex, NULL, NULL, &src.w, &src.h); // 获取纹理的长度和宽度

    SDL_Rect dst; // 目标位置
    dst.x = p_x;
    dst.y = p_y;
    dst.w = src.w;
    dst.h = src.h;
    SDL_RenderCopy(renderer, p_tex, &src, &dst);
}

void RenderWindow::render(Entity &p_entity)
{
    render(p_entity.getX(), p_entity.getY(), p_entity.getTex());
}

void RenderWindow::render(float p_x, float p_y, const char *p_text, TTF_Font *font, SDL_Color textColor)
{
   SDL_Surface* surfaceMessage = TTF_RenderText_Blended(font, p_text, textColor);
   SDL_Texture* message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
    SDL_Rect src;
    src.x = 0;
    src.y = 0;
    src.w = surfaceMessage->w;
    src.h = surfaceMessage->h;

    SDL_Rect dst;
    dst.x = p_x;
    dst.y = p_y;
    dst.w = src.w;
    dst.h = src.h;
   
       SDL_RenderCopy(renderer, message, &src, &dst);
		SDL_FreeSurface(surfaceMessage);
}
